/*
 * Alex Irlik, Steve Fox, TiOluwa Olarewaju, Derek Miller
 * Big-Ovacado Task Force
 * Version 1.0
 */
package bigo.todolist.avocado;

import bigo.todolist.avocado.TaskList.MyOnItemSelectedListener;
import android.os.Bundle;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;


/** 
 * Task adding page
 * @author Big Ohvocodo Task Force
 */

/*
 * An activity class to take in task information from a user and store the task in the database
 */
public class addATask extends Activity implements View.OnClickListener{
	Button addTask;
	Button cancel;
	ImageButton mapButton;
	EditText taskName;
	DatePicker date;
	EditText description;
	String username;
	Spinner spinner;
	String[] catList;
	String catSelected;
	double longitude;
	double latitude;
	String space = "";
	
	/**
	 * Initializations for when page loads
	 */
	protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState); 
			setContentView(R.layout.addatask); //Set the layout of the window
			
			idSet(); //Call method to set the ids for each variable
			
			//Receive info containing username
			Bundle recieveUsername = getIntent().getExtras();
			if(recieveUsername != null)
			{
				username = recieveUsername.getString("username"); //Set username
			}
			else
			{
				username = "test4"; //A test case for Junit testing
			}
			
			//create new database adaptor
			DBCategoryAdapter dbCat = new DBCategoryAdapter(this);
			dbCat.open();
			catList = dbCat.getCategory(false); //Get the proper category list to display for this activity
			dbCat.close();
			
			//This set of codes creates the spinner and places the category items in it
			ArrayAdapter <CharSequence> adapter = new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item );
		    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    for(int i = 0; i<catList.length; i++)
		    {
		    	adapter.add(catList[i]);
		    }
		    spinner.setAdapter(adapter);
			
		    //add listeners
			addTask.setOnClickListener(this); 
			mapButton.setOnClickListener(this);
			cancel.setOnClickListener(this); 
			spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
	}
	
	/**
	 * Instantiate UI variables
	 */
	private void idSet() {
		addTask = (Button) findViewById(R.id.addTaskButton); //Set id
		mapButton = (ImageButton) findViewById(R.id.mapsButton); //Set id
		cancel = (Button) findViewById(R.id.cancelButton); //Set id
		taskName = (EditText) findViewById(R.id.taskNameInput); //Set id
		date = (DatePicker) findViewById(R.id.dateInput); //Set id
		description = (EditText) findViewById(R.id.descriptionInput); //Set id
		spinner = (Spinner) findViewById(R.id.catspinner); //Set id
	}
	
	/**
	 * Actions to perform when given view is clicked
	 * 
	 * @param view - the view that was clicked upon
	 */
	public void onClick(View view) {
		
		//A switch case for the varying buttons
		switch(view.getId())
		{
			//Runs when the add a task button is clicked
			case R.id.addTaskButton:
				Editable task = taskName.getText(); //Gets the taskName from the EditText
				Editable desc = description.getText(); //Gets the description from the EditText
				String taskText = task.toString(); 
				String descText = desc.toString(); 
				
				//A check to make sure the field is not empty
				try{
					if (taskText.length() == 0 || descText.length() == 0) {
						Toast.makeText(addATask.this,"Please fill all fields", Toast.LENGTH_LONG).show();
					} 
					else {
						//If task and desc fields are field we continue
						DBTaskAdapter dbTask = new DBTaskAdapter(addATask.this);
						
						//Prepare the date materials
						
						int month = date.getMonth() +1;
						int day = date.getDayOfMonth();
						int year = date.getYear();
						
						if(Integer.valueOf(day) < 10)
                            space = "0";
						
						//Create a date string
						String myDate = ""+year + month + space + day;
						
						//Place the information in the database
						dbTask.open();
						dbTask.AddTask(username, taskText, myDate, descText, catSelected, "time",longitude,latitude, "false");
						dbTask.close();
						
						//Create a bundle to send back the username when starting the task activity again
						Intent ourIntent = new Intent(addATask.this, TaskList.class);
						Bundle sendUsername = new Bundle();
						sendUsername.putString("username", username);
						ourIntent.putExtras(sendUsername);
						//pop message to inform user of completion
						Toast.makeText(addATask.this,"Task Added", Toast.LENGTH_LONG).show();
						startActivity(ourIntent);
						
					}
					
				}catch(Exception e)
				{
					Toast.makeText(addATask.this,e.getMessage(), Toast.LENGTH_LONG).show();
				}
				break;
			
			//Case for when the maps button is clicked
			case R.id.mapsButton:
				Intent intent = new Intent();
                intent.setClass(addATask.this, MapsActivity.class);
                startActivityForResult(intent,0); //Start the maps activity for a result (longitude/latitude)
                break;
			
            //Case for when the cancel button is clicked    
			case R.id.cancelButton:
				Intent taskListIntent = new Intent(addATask.this, TaskList.class);
				Bundle sendUsername = new Bundle();
				sendUsername.putString("username", username);
				taskListIntent.putExtras(sendUsername);
				startActivity(taskListIntent); //Start the task list activity with a username bundle ^
				break;
		}
	}
	/**
	 * A simple procedure for adding tasks to the database
	 * @param taskName
	 * @param description
	 * @param month
	 * @param day
	 * @param year
	 * @return
	 */
	public boolean addTaskProcedure(String taskName, String description, int month, int day, int year){
		if (taskName == null || taskName.length() == 0){ // Check if the task field is filled
			return false;
		}
		if (description == null || description.length() == 0){ // Check if the task description is filled
			return false;
		}
		if (month == 0 || day == 0 || year == 0){
			return false;
		}
		DBTaskAdapter dbTask = new DBTaskAdapter(addATask.this);
		dbTask.open();
		if(Integer.valueOf(day) < 10)
            space = "0";
		
		String myDate = ""+year + month + space + day;
		
		if (dbTask.AddTask(username, taskName, myDate, description, catSelected, "time",longitude,latitude, "false") != 0){
			dbTask.close();
			return true;
		}
		else{
			dbTask.close();
			return false;
		}
		
		
		
	}
	/**
	 * Listener for selected items within the spinner
	 * @author BAT
	 *
	 */
	public class MyOnItemSelectedListener implements OnItemSelectedListener {
	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
	    {
			catSelected = parent.getItemAtPosition(pos).toString();	//The item currently selected is stored
	    	Toast.makeText(parent.getContext(), "The category selected is " + catSelected, Toast.LENGTH_LONG).show(); //The user is informed of what category is selected
	    }
	    
	    //A required method. The spinner does nothing when nothing is selected
	    public void onNothingSelected(AdapterView parent) {
	      // Do nothing.
	    }
	}
	
	/**
	 * Result method for when information is returned from the maps activity method.
	 *@param requestCode
	 *@param resultCode
	 *@param data
	 *
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK) //Checks if the information sent is ok
		{
			Bundle basket = data.getExtras(); //Obtain information
			longitude = basket.getDouble("longitude"); //Store longitude
			latitude = basket.getDouble("latitude"); //Store latitude
		}
	}
	
}
